<template>
  <div class="home">
    <HomeTopDisplay />

    <!-- 主要内容 -->
    <el-main class="main-content">
      <!-- 热门商品 -->
      <section class="hot-products-section">
        <div class="section-header">
          <h2>🔥 热门商品</h2>
          <el-button @click="$router.push('/products')" type="primary" plain>
            查看更多 <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
        <el-row :gutter="20">
          <el-col
              v-for="product in hotProducts"
              :key="product.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
          >
            <el-card
                class="product-card"
                shadow="hover"
                @click="handleProductClick(product)"
            >
              <div class="product-image">
                <img :src="product.image" :alt="product.name">
                <div class="product-overlay">
                  <el-button type="primary" size="small" @click.stop="addToCart(product)">
                    <el-icon><ShoppingCart /></el-icon>
                    加入购物车
                  </el-button>
                </div>
                <div class="product-badge" v-if="product.isAD">
                  <span class="badge-text">推荐</span>
                </div>
              </div>
              <div class="product-info">
                <h3 class="product-name">{{ product.name }}</h3>
                <p class="product-brand">{{ product.brand }}</p>
                <div class="product-price">
                  <span class="price">¥{{ formatPrice(product.price) }}</span>
                </div>
                <div class="product-stats">
                  <span class="sold">已售 {{ product.sold }}</span>
                  <span class="category">{{ product.category }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </section>

      <!-- 推荐商品 -->
      <section class="recommend-section">
        <div class="section-header">
          <h2>⭐ 为您推荐</h2>
        </div>
        <el-row :gutter="20">
          <el-col
              v-for="product in recommendProducts"
              :key="product.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
          >
            <el-card
                class="product-card"
                shadow="hover"
                @click="handleProductClick(product)"
            >
              <div class="product-image">
                <img :src="product.image" :alt="product.name">
                <div class="product-overlay">
                  <el-button type="primary" size="small" @click.stop="addToCart(product)">
                    <el-icon><ShoppingCart /></el-icon>
                    加入购物车
                  </el-button>
                </div>
                <div class="product-badge" v-if="product.isAD">
                  <span class="badge-text">推荐</span>
                </div>
              </div>
              <div class="product-info">
                <h3 class="product-name">{{ product.name }}</h3>
                <p class="product-brand">{{ product.brand }}</p>
                <div class="product-price">
                  <span class="price">¥{{ formatPrice(product.price) }}</span>
                </div>
                <div class="product-stats">
                  <span class="sold">已售 {{ product.sold }}</span>
                  <span class="category">{{ product.category }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </section>
    </el-main>

    <!-- 底部 -->
    <el-footer class="footer" height="auto">
      <div class="footer-content">
        <el-row :gutter="40">
          <el-col :span="8">
            <div class="footer-section">
              <h3>关于我们</h3>
              <p>周周淘商城致力于为您提供优质的购物体验</p>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="footer-section">
              <h3>客户服务</h3>
              <ul>
                <li>联系我们</li>
                <li>售后服务</li>
                <li>配送说明</li>
              </ul>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="footer-section">
              <h3>帮助中心</h3>
              <ul>
                <li>购物指南</li>
                <li>支付方式</li>
                <li>常见问题</li>
              </ul>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="footer-bottom">
        <p>&copy; 2024 周周淘商城. All rights reserved.</p>
      </div>
    </el-footer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowRight, ShoppingCart } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { getItemList } from '@/api/item'
import type { ItemDTO } from '@/api/item'
import { addItem2Cart } from '@/api/cart'
import type { CartFormDTO } from '@/api/cart'
import HomeTopDisplay from './components/HomeTopDisplay.vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const hotProducts = ref<ItemDTO[]>([])
const recommendProducts = ref<ItemDTO[]>([])

// 方法
const handleProductClick = (product: ItemDTO) => {
  router.push(`/product/${product.id}`)
}

const addToCart = async (product: ItemDTO) => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    const cartItem: CartFormDTO = {
      itemId: product.id!,
      num: 1, // 默认添加数量为1
      name: product.name,
      spec: product.spec,
      price: product.price,
      image: product.image
    };
    await addItem2Cart(cartItem);
    ElMessage.success('已添加到购物车');
  } catch (error) {
    console.error('添加购物车失败:', error);
    ElMessage.error('添加购物车失败');
  }
}

// 格式化价格（将分转换为元）
const formatPrice = (price: number) => {
  return (price / 100).toFixed(2)
}

// 获取商品数据
const loadProducts = async () => {
  try {
    // 获取热门商品（第一页）
    const hotResponse = await getItemList({
      pageNo: 1,
      pageSize: 8
    })

    const hotData = hotResponse.data
    if (hotData && hotData.code === 200 && hotData.data) {
      hotProducts.value = hotData.data.list || []
    } else if (hotData && hotData.list) {
      // 兼容旧格式
      hotProducts.value = hotData.list || []
    }

    // 获取推荐商品（第二页）
    const recommendResponse = await getItemList({
      pageNo: 2,
      pageSize: 8
    })

    const recommendData = recommendResponse.data
    if (recommendData && recommendData.code === 200 && recommendData.data) {
      recommendProducts.value = recommendData.data.list || []
    } else if (recommendData && recommendData.list) {
      // 兼容旧格式
      recommendProducts.value = recommendData.list || []
    }
  } catch (error) {
    console.error('加载商品失败:', error)
    ElMessage.error('加载商品失败')
  }
}

// 生命周期
onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.home {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 主要内容 */
.main-content {
  flex: 1;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 区块标题 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.section-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: bold;
}

/* 商品卡片 */
.product-card {
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;
}

.product-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.product-image {
  position: relative;
  height: 220px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .product-image img {
  transform: scale(1.08);
}

.product-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.product-card:hover .product-overlay {
  opacity: 1;
}

.product-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background: linear-gradient(45deg, #ff6b6b, #ee5a24);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.product-info {
  padding: 20px;
}

.product-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 600;
}

.product-brand {
  margin: 0 0 12px 0;
  color: #666;
  font-size: 14px;
}

.product-price {
  margin-bottom: 12px;
}

.price {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
  background: linear-gradient(45deg, #f56c6c, #ff6b6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.product-stats {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.sold {
  color: #409eff;
}

.category {
  color: #67c23a;
}

/* 底部 */
.footer {
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
  color: white;
  margin-top: 80px;
  padding: 0;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.footer-section h3 {
  margin-bottom: 15px;
  color: #ecf0f1;
  font-size: 18px;
}

.footer-section ul {
  list-style: none;
  padding: 0;
}

.footer-section li {
  margin-bottom: 8px;
  color: #bdc3c7;
  cursor: pointer;
  transition: color 0.3s ease;
}

.footer-section li:hover {
  color: #3498db;
}

.footer-bottom {
  border-top: 1px solid #34495e;
  padding: 20px;
  text-align: center;
  color: #bdc3c7;
}

/* 响应式 */
@media (max-width: 768px) {
  .main-content {
    padding: 15px;
  }

  .section-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>
